# gozerbot/utils/exception.py
#
#

""" generic functions """

__copyright__ = 'this file is in the public domain'

# ==============
# IMPORT SECTION

# gozerbot imports
from gozerbot.utils.log import rlog
from gozerbot.utils.locking import lockdec

# basic imports
import sys, traceback, logging, thread, os

# END IMPORT
# ==========

# ============
# LOCK SECTION

exceptionlock = thread.allocate_lock()
exceptionlocked = lockdec(exceptionlock)

borkonexception = False

# END LOCK
# ========

@exceptionlocked
def exceptionmsg():
    exctype, excvalue, tb = sys.exc_info()
    trace = traceback.extract_tb(tb)
    result = ""
    for i in trace:
        fname = i[0]
        linenr = i[1]
        func = i[2]
        result += "%s:%s %s | " % (fname, linenr, func)
    del trace
    res = "%s%s: %s" % (result, exctype, excvalue)
    if res not in exceptionlist:
        exceptionlist.append(res)
    if '_props' in res:
        print 
    return res

def handle_exception(event=None, log=True, short=False, txt=""):
    global borkonexception
    errormsg = exceptionmsg()

    if event:
       if '_props' in errormsg:
           print "YOOOOOOOOOOOO"
           print event
           os._exit(1)

    if log:
        rlog(1000, 'EXCEPTION', errormsg)

    if event:

        if borkonexception:
            rlog(1000, 'EXCEPTION', 'command: ' + event.txt)
            rlog(1000, 'EXCEPTION', 'options: ' + str(event.options))

        exceptionevents.append((event, errormsg))

        if event.bot:
            event.bot.error = errormsg

        event.reply(errormsg)

    if borkonexception:
        rlog(1000, 'EXCEPTION', "BORK ON EXCEPTION")
        sys.stdout.flush()
        os._exit(1)

# ============
# INIT SECTION

exceptionlist = []
exceptionevents = []

# END INIT
# ========
